package com.pliu.sqlSession;

import com.pliu.io.Resources;
import com.pliu.pojo.Configuration;
import com.pliu.pojo.MappedStatement;

import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @ClassName DefaultSqlSession
 * @Description TODO
 * @Author pliu
 * @Date 2020/6/21 16:06
 * @Version 1.0
 **/
public class DefaultSqlSession implements SqlSession{
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 查询所有
     *
     * @param statementId
     * @param params
     */
    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        Executor executor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<E> list = executor.query(configuration,mappedStatement,params);
        return list;
    }

    /**
     * 查询单个
     *
     * @param statementId
     * @param params
     */
    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (null != objects && objects.size() == 1) {
            return (T) objects.get(0);
        } else if (null != objects && objects.size() == 0){
            return null;
        } else if (null == objects){
            throw new RuntimeException("查询返回结果为空");
        } else {
            throw new RuntimeException("查询返回结果大于一条");
        }
    }

    /**
     * 执行insert、update和delete操作
     *
     * @param statementId
     * @param params
     */
    @Override
    public int update(String statementId, Object... params) throws Exception {
        Executor executor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int count = executor.update(configuration,mappedStatement,params);
        return count;
    }

    /**
     * 生成代理对象
     *
     * @param mapperClass
     * @return
     */
    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用jdk动态代理为Dao接口生成代理对象,并返回
        Object newProxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String statementId = method.getDeclaringClass().getName()+"."+method.getName();
                //method.getGenericReturnType()方法返回值类型   instanceof ParameterizedType是否包含泛型 包含则是list
                if (method.getGenericReturnType() instanceof ParameterizedType) {
                    return selectList(statementId, args);
                } else if ("insert".equals(method.getName())
                        || "update".equals(method.getName())
                        || "delete".equals(method.getName())) { //增删改操作
                    return update(statementId, args);
                }
                return selectOne(statementId, args);

            }
        });
        return (T) newProxyInstance;
    }
}
